package com.lzx.java.nio;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Client1Main {

	public static void main(String[] args) throws IOException {

		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		Selector selector = Selector.open();

		serverSocketChannel.socket().bind(new InetSocketAddress(8080));
		serverSocketChannel.configureBlocking(false);
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

		while (true) {
			selector.select();

			Iterator<SelectionKey> iterator = selector.selectedKeys()
					.iterator();
			while (iterator.hasNext()) {
				SelectionKey selectionKey = iterator.next();
				iterator.remove();

				if (selectionKey.isAcceptable()) {
					System.out.println("isAcceptable");
					ServerSocketChannel server = (ServerSocketChannel) selectionKey
							.channel();
					SocketChannel channel = server.accept();
					channel.configureBlocking(false);
					channel.register(selector, SelectionKey.OP_READ);

				}
				if (selectionKey.isReadable()) {
					System.out.println("isReadable");

					SocketChannel channel = (SocketChannel) selectionKey
							.channel();

					ByteBuffer byteBuffer = ByteBuffer.allocate(2);

					int ret = channel.read(byteBuffer);
					System.out.println("ret:" + ret);
					System.out.println(byteBuffer.toString());
//					System.out.println(byteBuffer.getInt());

				}
				
				
				
			}

		}
	}

}
